package com.heima.user;

import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class YongyouAiDemo {

    @Test
    public void idCardCheck(){
        Map map = idCardOcr("https://hmtt122.oss-cn-shanghai.aliyuncs.com/demo_idcard.png");
        System.out.println(map);
    }

    /**
     * 扫描身份证的信息
     */
    private Map idCardOcr(String idCardUrl){
        try {
            Map params = new HashMap();
            params.put("image",idCardUrl);
            params.put("imageType","URL");
            params.put("ocrType","0");   //0表示正面 1表示反面
            Map map = executePostReq("71689be5af2541cdafcf124acd01e98d", "https://api.yonyoucloud.com/apis/dst/IdcardOCR/IdcardOCR", params);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用接口失败");
            return null;
        }
    }





    /**
     *  检查身份证的方法
     * @param idNumber  身份证号
     * @param userName   姓名
     * @return
     */
    private Boolean idCardCheck(String idNumber,String userName){
        try {
            Map params = new HashMap();
            params.put("idNumber",idNumber);
            params.put("userName",userName);
            Map map = executePostReq("60baafda420e4549b58869801b60159b", "https://api.yonyoucloud.com/apis/dst/matchIdentity/matchIdentity", params);
            return (boolean) map.get("success");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用接口失败");
            return false;
        }
    }




    /**
     *  基础的post请求
     * @param apicode  用有密钥
     * @param url   要调用接口路径
     * @param params 请求参数
     * @return
     */
    private Map executePostReq(String apicode,String url,Map params){
        //1.创建restTemplate客户端
        RestTemplate restTemplate = new RestTemplate();
        //2.封装请求头信息  apicode  contentType
        HttpHeaders headers = new HttpHeaders();
        headers.set("apicode",apicode);
        headers.setContentType(MediaType.APPLICATION_JSON);
        //3.封装请求参数  map  idNumber  userName
        HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(params), headers);
        //4.发起请求调用  得到返回结果
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        //5.将返回结果转为map对象
        String body = responseEntity.getBody();
        Map result = JSON.parseObject(body, Map.class);
        System.out.println(result);
        return result;
    }
}
